package edu.sdufe.controller;

import edu.sdufe.pojo.User;
import edu.sdufe.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// 导入Jakarta EE的HttpSession (Spring Boot 3.x使用)
import jakarta.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户登录接口
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        User loginUser = userService.login(user.getUsername(), user.getPassword());
        if (loginUser != null) {
            // 登录成功，将用户信息存入session
            session.setAttribute("user", loginUser);
            result.put("success", true);
            result.put("message", "登录成功");
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }

        return result;
    }

    // 用户登出接口
    @PostMapping("/logout")
    public Map<String, Object> logout(HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 清除session
        session.invalidate();

        result.put("success", true);
        result.put("message", "已成功登出");

        return result;
    }
}